const express = require('express');
const router = express.Router();
const db = require('../db/index.js');
const { authToken } = require('../middleware/authMddleware.js');

// 添加token鉴权
// router.use(authToken);

// 获取所有商品数据
router.get('/list', async (req, res) => {
  const { pageNo = 1, pageSize = 10 } = req.query;
  try {
    const fieldSql = `SELECT COLUMN_NAME
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_NAME = 'products'
      AND COLUMN_NAME != 'product_id'`;

    const [fields] = await db.query(fieldSql);
    const fieldStr = fields.map((e) => e.COLUMN_NAME);
    let str = [];
    fieldStr.forEach((e) => {
      if (
        !str.includes(e) &&
        !['id', 'create_time', 'update_time'].includes(e)
      ) {
        str.push(e);
      }
    });
    console.log('fields', fields, fieldStr, str, str.join(', '));

    const sql = `SELECT ${str}, product_id as id FROM products LIMIT ?, ?`;
    const [list] = await db.query(`SELECT * FROM products`);
    const [products] = await db.query(sql, [
      (pageNo - 1) * pageSize,
      +pageSize,
    ]);
    res.json({
      code: 0,
      data: {
        data: products,
        total: list.length,
      },
      message: '获取商品数据成功',
    });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error', message: error });
  }
});

// 添加商品
router.post('/add', async (req, res) => {
  const { name, price, stock, description = '' } = req.body;
  // 验证必要参数是否存在
  if (!name || !price || !stock) {
    return res.status(400).json({
      code: -1,
      error: '商品名称必填, 价格必填, 库存必填',
    });
  }

  try {
    const insertSql =
      'INSERT INTO products (name, price, stock, description) VALUES (?,?,?,?)';
    await db.execute(insertSql, [name, +price, +stock, description]);
    res.status(200).json({
      code: 0,
      message: '商品添加成功',
    });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error', message: error });
  }
});

// 更新商品
router.post('/update', async (req, res) => {
  const { id, name, price, stock, description = '' } = req.body;
  if (!id) {
    return res.status(400).json({
      code: -1,
      error: 'id 必填',
    });
  }
  try {
    const sql = `SELECT * FROM products WHERE product_id = ?`;
    const [products] = await db.query(sql, [id]);
    console.log('products', products);

    if (products.length === 0) {
      return res.status(200).json({
        code: -1,
        error: '该商品不存在',
      });
    } else {
      const {
        name: name1,
        price: price1,
        stock: stock1,
        description: description1,
      } = products[0];
      const updateSql = `UPDATE products SET name=?, price=?, stock=?, description=? WHERE product_id=?`;
      await db.execute(updateSql, [
        name || name1,
        +price || price1,
        +stock || stock1,
        description || description1,
        id,
      ]);
      res.status(200).json({
        code: 0,
        message: '商品更新成功',
      });
    }
  } catch (error) {
    res.status(500).json({ error: 'Internal server error', message: error });
  }
});

// 删除商品
router.delete('/delete', async (req, res) => {
  const { id } = req.query;
  if (!id && !`${id}`) {
    return res.status(200).json({
      code: -1,
      message: 'Id 必填',
    });
  }
  try {
    const sql = 'SELECT * FROM products WHERE product_id = ?';
    const [products] = await db.query(sql, [id]);
    if (products.length === 0) {
      return res.status(200).json({
        code: -1,
        error: '该商品不存在',
      });
    }
    const deleteSql = 'DELETE FROM products WHERE product_id = ?';
    await db.execute(deleteSql, [id]);
    res.status(200).json({
      code: 0,
      message: '商品删除成功',
    });
  } catch (error) {
    res.status(500).json({ error: 'Internal server error', message: error });
  }
});

module.exports = router;
